<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="联系人" prop="contactName">
        <el-input v-model="queryParams.contactName" placeholder="请输入联系人姓名" clearable />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option label="待确认" value="0" />
          <el-option label="已确认" value="1" />
          <el-option label="已取消" value="2" />
          <el-option label="已完成" value="3" />
        </el-select>
      </el-form-item>
      <el-form-item label="预约日期" prop="reservationDate">
        <el-date-picker
          v-model="queryParams.reservationDate"
          type="date"
          placeholder="选择日期"
          value-format="yyyy-MM-dd"
          style="width: 140px"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete">删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="reservationList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" width="80" />
      <el-table-column label="联系人" align="center" prop="contactName" />
      <el-table-column label="联系电话" align="center" prop="contactPhone" />
      <el-table-column label="服务类型" align="center" prop="serviceType.name" />
      <el-table-column label="预约日期" align="center" prop="reservationDate" width="100" />
      <el-table-column label="预约时间" align="center" prop="reservationTime" width="100" />
      <el-table-column label="状态" align="center" prop="status" width="100">
        <template slot-scope="scope">
          <el-tag :type="statusTypeMap[scope.row.status]">{{ statusMap[scope.row.status] }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-if="scope.row.status === '0'">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-check" @click="handleConfirm(scope.row)" v-if="scope.row.status === '0'">确认</el-button>
          <el-button size="mini" type="text" icon="el-icon-close" @click="handleCancel(scope.row)" v-if="scope.row.status === '0' || scope.row.status === '1'">取消</el-button>
          <el-dropdown @command="(command) => handleStatusChange(scope.row, command)" trigger="click">
            <span class="el-dropdown-link">
              <el-button size="mini" type="text" icon="el-icon-arrow-down">更改状态</el-button>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="0" v-if="scope.row.status !== '0' && scope.row.status !== '2' && scope.row.status !== '3'">待确认</el-dropdown-item>
              <el-dropdown-item command="1" v-if="scope.row.status !== '1' && scope.row.status !== '2' && scope.row.status !== '3'">已确认</el-dropdown-item>
              <el-dropdown-item command="2" v-if="scope.row.status !== '2' && scope.row.status !== '3'">已取消</el-dropdown-item>
              <el-dropdown-item command="3" v-if="scope.row.status !== '3' && scope.row.status !== '2'">已完成</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="联系人" prop="contactName">
          <el-input v-model="form.contactName" placeholder="请输入联系人姓名" />
        </el-form-item>
        <el-form-item label="联系电话" prop="contactPhone">
          <el-input v-model="form.contactPhone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="服务类型" prop="serviceTypeId">
          <el-select v-model="form.serviceTypeId" placeholder="请选择服务类型" style="width: 100%">
            <el-option
              v-for="item in serviceTypeOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="预约日期" prop="reservationDate">
          <el-date-picker
            v-model="form.reservationDate"
            type="date"
            placeholder="选择日期"
            value-format="yyyy-MM-dd"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="预约时间" prop="reservationTime">
          <el-time-picker
            v-model="form.reservationTime"
            format="HH:mm"
            placeholder="选择时间"
            value-format="HH:mm"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注信息" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 取消预约对话框 -->
    <el-dialog title="取消预约" :visible.sync="cancelOpen" width="400px" append-to-body>
      <el-form ref="cancelForm" :model="cancelForm" :rules="cancelRules" label-width="80px">
        <el-form-item label="取消原因" prop="reason">
          <el-input v-model="cancelForm.reason" type="textarea" placeholder="请输入取消原因" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitCancel">确 定</el-button>
        <el-button @click="cancelOpen = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listReservations, getReservation, addReservation, updateReservation, delReservation, confirmReservation, cancelReservation } from "@/api/company/reservation";
import { listServiceTypes } from "@/api/company/serviceType";

export default {
  name: "ReservationManage",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      reservationList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示取消弹出层
      cancelOpen: false,
      // 状态映射
      statusMap: {
        "0": "待确认",
        "1": "已确认",
        "2": "已取消",
        "3": "已完成"
      },
      // 状态类型映射
      statusTypeMap: {
        "0": "warning",
        "1": "success",
        "2": "danger",
        "3": "info"
      },
      // 服务类型选项
      serviceTypeOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        contactName: null,
        status: null,
        reservationDate: null
      },
      // 表单参数
      form: {},
      // 取消表单参数
      cancelForm: {
        id: null,
        reason: null
      },
      // 表单校验
      rules: {
        contactName: [
          { required: true, message: "联系人姓名不能为空", trigger: "blur" }
        ],
        contactPhone: [
          { required: true, message: "联系电话不能为空", trigger: "blur" },
          { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号码", trigger: "blur" }
        ],
        serviceTypeId: [
          { required: true, message: "服务类型不能为空", trigger: "change" }
        ],
        reservationDate: [
          { required: true, message: "预约日期不能为空", trigger: "change" }
        ],
        reservationTime: [
          { required: true, message: "预约时间不能为空", trigger: "change" }
        ]
      },
      // 取消表单校验
      cancelRules: {
        reason: [
          { required: true, message: "取消原因不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getServiceTypeOptions();
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.loading = true;
      listReservations(this.queryParams).then(response => {
        this.reservationList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 获取服务类型选项
    getServiceTypeOptions() {
      listServiceTypes({ pageSize: 100, status: "0" }).then(response => {
        this.serviceTypeOptions = response.rows;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        contactName: null,
        contactPhone: null,
        serviceTypeId: null,
        reservationDate: null,
        reservationTime: null,
        remark: null,
        status: "0"
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length!==1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加预约";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids[0];
      getReservation(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改预约";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateReservation(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addReservation(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除预约编号为"' + ids + '"的数据项？').then(function() {
        return delReservation(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 确认预约操作 */
    handleConfirm(row) {
      this.$modal.confirm('是否确认该预约？').then(function() {
        return confirmReservation(row.id, "1");
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("预约已确认");
      }).catch(() => {});
    },
    /** 取消预约操作 */
    handleCancel(row) {
      this.cancelForm = {
        id: row.id,
        reason: null
      };
      this.cancelOpen = true;
    },
    /** 提交取消 */
    submitCancel() {
      this.$refs["cancelForm"].validate(valid => {
        if (valid) {
          cancelReservation(this.cancelForm.id, this.cancelForm.reason).then(response => {
            this.$modal.msgSuccess("预约已取消");
            this.cancelOpen = false;
            this.getList();
          });
        }
      });
    },
    /** 更改状态操作 */
    handleStatusChange(row, command) {
      // 准备状态文本说明
      let statusText = this.statusMap[command];
      this.$modal.confirm('是否确认将预约状态更改为"' + statusText + '"？').then(function() {
        return confirmReservation(row.id, command);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("预约状态已更新为：" + statusText);
      }).catch(() => {});
    }
  }
};
</script> 